class NotifyRegistryCenter {
    constructor() { this.queue = {}; }
}
const notify = new NotifyRegistryCenter();
/*
 功能: 遍历队列，根据具体标记通知监听者触发回调。使用时需要先add，不需要时一定要remove。
 flag: 自定义标记，
 callAction: 触发的回调事件
 caller: 监听者。同一个标记可以有多个caller
 */
module.exports = {
    notify: (flag, params) => {
        if (flag) {
            const list = notify.queue[flag];
            if (!list) { return false; }
            for (let i = 0; i < list.length; i++) {
                const action = list[i].action;
                action && action(params);
            }
        }
        return true;
    },
    addNotifier: (flag, callAction, caller) => {
        if (!flag || !callAction || !caller) {
            return false;
        }
        let list;
        list = notify.queue[flag];
        if (!list) { list = []; }

        for (let i = 0; i < list.length; i++) {
            if (list[i].action === callAction && list[i].caller === caller) { // 已经存在的话，不必重复
                return false;
            }
        }
        list.push({ action: callAction, caller });
        notify.queue[flag] = list;// 保存
        return true;
    },
    removeNotifier: (flag, callAction, caller) => {
        if (!flag) {
            return false;
        }

        const list = notify.queue[flag];
        if (!list) { return false; }
        if (!callAction || !caller) {
            delete notify.queue[flag];
            return true;
        }
        for (let i = 0; i < list.length; i++) {
            if (list[i].action === callAction && list[i].caller === caller) {
                list.splice(i, 1);
                break;
            }
        }
        if (list.length === 0) {
            delete notify.queue[flag];
        } else {
            notify.queue[flag] = list;
        }
        return true;
    },


};
